package com.zlq.cn.service.un;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlq.cn.admin.domain.SysConfig;
import com.zlq.cn.admin.service.SysConfigService;
import com.zlq.cn.config.Config;
import com.zlq.cn.entity.CityOpen;
import com.zlq.cn.mapper.un.CityOpenMapper;
import com.zlq.cn.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 城市开放列表 服务实现类
 * </p>
 *
 * @author zhoucl
 * @since 2022-12-15
 */
@Slf4j
@Service
public class CityOpenService extends ServiceImpl<CityOpenMapper, CityOpen> {
    private static final String FORMAT = "yyyy-MM-dd HH:mm:ss";
    @Resource
    private SysConfigService sysConfigService;

    /**
     * 这里可能要你写一下逻辑 返回的数据要改一下。
     * 1、随机的token(不会用到,跟token有点像就行)
     * 2、refreshToken(放开关,现在写死传NO）
     * YES 传 fkgXunLouZ5uVQvjNlG1nA==
     * NO 传 8+GH3qUr3VSzBqmWvITAMQ==
     * 3、还有一个expireToken(放链接的加密) CfhorI9R3fF/LmXwuDHGD92zVk2xfM/niqS2cqziXZLmEV1FFCSD7u8FA8K3UbF5
     */
    public boolean checkOpen(HttpServletRequest request) {
        try {
            String ipAddr = IpUtils.getIpAddr(request);
            log.info("当前查询ip：" + ipAddr);
            String json = HttpUtil.get("https://api.vore.top/api/IPdata?ip=" + ipAddr);
            log.info("当前查询ip对应数据：" + json);
            JSONObject body = JSON.parseObject(json);
            if (body.containsKey("adcode")) {
                String cityCode = body.getJSONObject("adcode").getString("a");
                cityCode = cityCode.substring(0, 2) + "0000";
                Set<String> cityCodes = super.lambdaQuery()
                        .eq(CityOpen::getOpen, 1)
                        .eq(CityOpen::getCityCode, cityCode)
                        .list().stream().map(CityOpen::getCityCode)
                        .collect(Collectors.toSet());
                SysConfig sysConfig = sysConfigService.getById(SysConfigService.CONFIG_CITY_TIME);
                if (cityCodes.contains(cityCode) && StringUtils.isNotEmpty(sysConfig.getValue()) && StringUtils.isNotEmpty(sysConfig.getValueExt())) {
                    LocalDateTime beginTime = LocalDateTimeUtil.parse(sysConfig.getValue(), FORMAT);
                    LocalDateTime endTime = LocalDateTimeUtil.parse(sysConfig.getValueExt(), FORMAT);
                    LocalDateTime now = LocalDateTime.now();
                    if (beginTime.compareTo(now) <= 0 && now.compareTo(endTime) <= 0) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            log.error("城市开关获取失败", e);
        }
        return false;
    }

    public static void main(String[] args) {
        String cityCode = "440300";
        cityCode = cityCode.substring(0, 2) + "0000";
        System.out.println(cityCode);
    }

    public boolean insert(CityOpen cityOpen) {
//        Integer count = super.lambdaQuery()
//                .eq(CityOpen::getCityCode, cityOpen.getCityCode())
//                .eq(CityOpen::getProject, Config.PROJECT_AIZH)
//                .count();
//        Assert.state(count == null || count == 0, "该城市已添加");
        cityOpen.setProject(Config.PROJECT_AIZH);
        LambdaQueryWrapper<CityOpen> wrapper = new LambdaQueryWrapper<CityOpen>()
                .eq(CityOpen::getCityCode, cityOpen.getCityCode())
                .eq(CityOpen::getProject, Config.PROJECT_AIZH);
        if (!super.update(cityOpen, wrapper)) {
            return super.save(cityOpen);
        }
        return Boolean.TRUE;
    }
}
